package com.apes.framework.plugin.esb.processor.mapping.parser.model;

import com.apes.framework.jpa.ApesBean;
import com.apes.framework.util.CacheUtil;
import com.apes.framework.util.ReflectUtil;
import com.apes.framework.util.Tools;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

@Data
public class Field {

    private String attrname = null;
    private String fieldtype = null;
    private String width = null;
    private String decimals = null;
    private String target = null;
    private String defaultValue = null;
    private String allownull = null;
    private String name = null;
    private String format = null;
    private String check = null;
    private String length = null; //长度限制
    private String pack = null;
    private String demolish = null;

    public <T> T convert(Object value) {
        return (T) Tools.convert(fieldtype, value);
    }

    public <T> T pack(Object value) {
        Map<String, Object> result = new HashMap<>();
        result.put(pack, value);
        return (T) result;
    }

    public <T> T demolish(Object value) {
        if (value == null) return null;
        if (value instanceof Map) {
            try {
                return (T) CacheUtil.getEngine().execute(demolish, value);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return ReflectUtil.getFieldValue(value, demolish);
    }

}
